﻿
using HBase;
using hconnect;
using MongoDB.Bson.Serialization;
using System;
using System.Collections.Generic;
using System.IO;

namespace hCommand
{
    public abstract class JobAbleTask : ZtTask, Job {
        public abstract SocketZtTaskConnect getTaskConnect(BaseTask taskModel);
        protected ICoreTaskServer coreTaskServer = WMSDalFactray.getDal<ICoreTaskServer>();
        
        public virtual bool beforeSend(List<BaseTask> taskModels)
        {
            foreach (var taskModel in taskModels)
            {
                if (null == taskModel)
                    continue;
                int count = coreTaskServer.beginTask(taskModel);
                if (count != 1)
                {
                    fileAll(InfoCode.fileAll_task_send_before, "{0}update_param_error ", taskModel.taskNo);
                    return false;
                }
            }
            return true;

        }
        public bool DoOutAndShiftTask(List<BaseTask> taskModels)
        {

            //修改wms任务表为下发完成
            if (!beforeSend(taskModels))
            {
                return false;
            }

            return send(taskModels);
        }

        public bool doTask(BaseTask bt)
        {
            if (bt == null)
            {
                return false;
            }
            var tms = new List<BaseTask> { bt };
            return DoOutAndShiftTask(tms);
        }



        public virtual bool send(List<BaseTask> taskModels)
        {
            foreach (var taskModel in taskModels)
            {

                SocketZtTaskConnect conn = getTaskConnect(taskModel);
                int begin = getBegin(taskModel);
                bool res = conn.sendTask(taskModel, begin);
                if (res)
                {
                    oneTimeSleep = StatusCache.signalLife;
                    continue;
                }
                else
                {
                    fileAll(InfoCode.fileAll_task_send_after_error, "{0} at {1}Send_error", taskModel.taskNo, taskModel.src);
                    continue;
                }
            }
            return true;
        }
        public virtual int getBegin(BaseTask bt)
        {

            int src = Math.Abs(bt.src);
            PlcCarrierPoint point = PlcCarrierPoint.getPlcCarrierPoint(src);
            if (point == null)
            {
                throw new Exception(src + "无法找到发送地址站台");
            }
            return point.WOffset;
        }
    }
}
